package com.spzx.order.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.domain.CartInfo;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.configure.DelayedMqConfig;
import com.spzx.order.domain.*;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.OrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.domain.SkuLockVo;
import com.spzx.user.api.RemoteUserInfoService;
import com.spzx.user.domain.UserAddress;
import com.spzx.user.domain.UserInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Resource
    private RemoteCartService remoteCartService;

    @Resource
    private RemoteProductService remoteProductService;

    @Resource
    private RemoteUserInfoService remoteUserInfoService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Resource
    private OrderLogMapper orderLogMapper;

    @Resource
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RabbitService rabbitService;

    @Override
    public TradeVo trade(Long userId) {
        TradeVo tradeVo = new TradeVo();
        R<List<CartInfo>> cartInfoListR = remoteCartService.getCartCheckedList(userId, "inner");
        List<CartInfo> cartInfoList = cartInfoListR.getData();
        BigDecimal totalAmount = new BigDecimal(0);
        for (CartInfo cartInfo : cartInfoList) {
            totalAmount = totalAmount.add(cartInfo.getSkuPrice().multiply(BigDecimal.valueOf(cartInfo.getSkuNum())));
        }
        List<OrderItem> orderItemList = cartInfoList.stream().map(new Function<CartInfo, OrderItem>() {
            @Override
            public OrderItem apply(CartInfo cartInfo) {
                OrderItem orderItem = new OrderItem();
                BeanUtils.copyProperties(cartInfo, orderItem);
                orderItem.setSkuPrice(cartInfo.getSkuPrice());
                return orderItem;
            }
        }).toList();

        String tradeNo = generateTradeNo(userId);

        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTradeNo(tradeNo);
        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        Boolean isValid = checkTradeNo(orderForm.getTradeNo(), userId);
        //验证流水号
        if(!isValid){
            throw new RuntimeException("请勿重复提交订单，请尝试重试");
        }
        //删除流水号
        deleteTradeNo(userId);

        //2. 判断购物项
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        if (orderItemList == null){
            throw new RuntimeException("购物项为空，请求不合法");
        }

        //3.订单校验
        //3.1.校验价格（判断商品是不是MySQL数据库中最新价格）
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        R<List<ProductSku>> productSkuListR = remoteProductService.getSkuPriceList(skuIdList, "inner");
        List<ProductSku> productSkuList = productSkuListR.getData();
        Map<Long, BigDecimal> salePriceMap = productSkuList.stream().collect(Collectors.toMap(ProductSku::getId, ProductSku::getSalePrice));
        for (OrderItem orderItem : orderItemList) {
            if(orderItem.getSkuPrice().compareTo(salePriceMap.get(orderItem.getSkuId())) != 0){
                //更新购物车价格
                remoteCartService.updateCartPrice(userId, "inner");
                throw new RuntimeException(orderItem.getSkuName() + "价格发生变化");
            }
        }

        //3.2.校验库存并锁定库存
        String tradeNo = orderForm.getTradeNo();
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(new Function<OrderItem, SkuLockVo>() {
            @Override
            public SkuLockVo apply(OrderItem orderItem) {
                SkuLockVo skuLockVo = new SkuLockVo();
                skuLockVo.setSkuId(orderItem.getSkuId());
                skuLockVo.setSkuNum(orderItem.getSkuNum());
                return skuLockVo;
            }
        }).toList();
        R<String> checkAndLockR = remoteProductService.checkAndLock(tradeNo, skuLockVoList, "inner");
        String message = checkAndLockR.getData();
        Assert.isTrue(Objects.equals(message, ""), message);

        //4.下单
        Long orderId = 0L;
        try{
            orderId = saveOrder(orderForm);
        }catch (Exception e){
            throw new RuntimeException("订单创建失败");
        }

        //5.删除购物车中对应的购物项
        remoteCartService.deleteCartCheckedList(userId, "inner");


        //发送延迟消息队列，到期后，修改订单状态
        rabbitService.sendDelayMessage(DelayedMqConfig.exchange_delay, DelayedMqConfig.routing_delay, orderId + "");

        return orderId;
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        return baseMapper.selectById(orderId);
    }

    public Long saveOrder(OrderForm orderForm){

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        Long userId = SecurityContextHolder.getUserId();
        //1.保存订单信息
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        R<UserInfo> userInfoR = remoteUserInfoService.getUserInfoByUserId(userId, "inner");
        UserInfo userInfo = userInfoR.getData();
        orderInfo.setNickName(userInfo.getUsername());
        orderInfo.setOrderNo(orderForm.getTradeNo());
//        orderInfo.setCouponId();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(new BigDecimal("0.00"));
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setFeightFee(new BigDecimal("0.00"));
        orderInfo.setOrderStatus(0);

        R<UserAddress> userAddressR = remoteUserInfoService.getUserAddress(orderForm.getUserAddressId(), "inner");
        UserAddress userAddress = userAddressR.getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        baseMapper.insert(orderInfo);;
        //2.保存订单项信息
        orderItemList.forEach(orderItem -> {
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        });

        //3‘保存订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setNote("提交订单");
        orderLog.setOrderId(orderInfo.getId());
        //orderLog.setOperateUser();
        orderLog.setProcessStatus(0L);
        orderLogMapper.insert(orderLog);
        return orderInfo.getId();
    }

    public String generateTradeNo(Long userId){
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2、构建流水号value
        String tradeNo = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set(userTradeKey, tradeNo, 5, TimeUnit.MINUTES);
        return tradeNo;
    }

    /**
     * 验证流水号是否有效
     */

    public Boolean checkTradeNo(String tradeNo, Long userId){
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        String redisTradeNo = redisTemplate.opsForValue().get(userTradeKey);
        return tradeNo.equals(redisTradeNo);
    }

    /**
     * 删除流水号
     */
    public void deleteTradeNo(Long userId){
        String userTradeKey = "user:tradeNo:" + userId;
        redisTemplate.delete(userTradeKey);
    }
}
